﻿using HinduShop.DbClassLib.Mappings;
using NHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace HinduShop.DbClassLib
{
    /// <summary>
    /// Это должно быть Unit of Work
    /// </summary>
    public class SessionManager
    {
        private Configuration Config;
        private ISessionFactory SessionFactory;
        private ISession Session;

        public Configuration Configuration
        {
            get { return Config; }
        }

        public SessionManager()
        {
            Configure();
            SessionFactory = InitSessionFactory();
        }

        public IRepository<T> CreateRepository<T>() where T : class
        {
            return new ModelsRepository<T>(/*this*/);
        }

        private ISessionFactory InitSessionFactory()
        {
            return Config.BuildSessionFactory();
        }

        private void Configure()
        {
            Config = Fluently.Configure().
                Database(
                    MsSqlConfiguration
                        .MsSql2008
                        .ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
                            .UseReflectionOptimizer()
                            )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductMap>())
                .BuildConfiguration();
        }

        public ISession OpenSession()
        {
            if (Session == null)
            {
                Session = SessionFactory.OpenSession();
            }
            return Session;
        }

        public void CloseSession()
        {
            if (Session != null && Session.IsOpen)
            {
                Session.Flush();
                Session.Close();
            }
        }

        public ITransaction BeginTransaction()
        {
            return OpenSession().BeginTransaction();
        }
    }
}